/*
 * @Author: 范志伟
 * @Date: 2025-03-20 16:57:26
 * @LastEditors: 范志伟
 * @LastEditTime: 2025-04-23 11:20:50
 * @FilePath: \common-web-ui\src\utils\websocket.js
 * @Description: websocket
 */
import store from "../store";
const SOCKET_READYSTATE = "1";
// 创建一个单例 WebSocket 管理器
let socketInstance = null;
let socketKeep = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 10;
const RECONNECT_DELAY = 3000;
const PING_INTERVAL = 10000;
/**
 * 获取 WebSocket 连接
 * @param {string} host - WebSocket 服务器地址
 * @returns {WebSocket} - WebSocket 实例
 */
export default function getWebSocket(host) {
  // 如果已存在连接，先关闭
  if (socketInstance) {
    closeWebSocket();
  }
  // 实例化socket  创建新连接
  const wsServer = `${
    location.protocol === "https:" ? "wss" : "ws"
  }://${host}/webSocket`;
  socketInstance = new WebSocket(wsServer);
  // 保存到全局对象
  window.systemSocket = socketInstance;
  let pong = false;
  // 监听连接打开
  socketInstance.onopen = () => {
    console.log("主socket连接成功");
    pong = true;
    reconnectAttempts = 0;
    // 发送用户标识
    try {
      const userId = store.getters.userInfo.userId;
      const industryCode = store.getters.userInfo.industryCode;
      socketInstance.send(
        JSON.stringify({
          uid: `${userId}-${industryCode}`,
        })
      );
    } catch (err) {
      console.error("发送用户标识失败:", err);
    }
    // 设置心跳检测
    clearInterval(socketKeep);
    socketKeep = setInterval(() => {
      if (!pong) {
        console.warn("WebSocket心跳检测失败，尝试重连");
        clearInterval(socketKeep);
        closeWebSocket();
        if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
          reconnectAttempts++;
          setTimeout(() => getWebSocket(host), RECONNECT_DELAY);
        } else {
          console.error(`WebSocket重连失败，已尝试${MAX_RECONNECT_ATTEMPTS}次`);
        }
        return;
      }

      pong = false;
      socketInstance.send("ping");
    }, PING_INTERVAL);
  };
  // 监听socket错误信息
  window.systemSocket.onerror = (err) => {
    console.error("WebSocket连接错误:", err);
  };
  // 监听socket关闭监听
  window.systemSocket.onclose = () => {
    pong = false;
    console.log("主socket连接关闭");
  };
  // 监听socket接收的信息
  window.systemSocket.onmessage = (data) => {
    if (!data || data?.data === "pong") {
      pong = true;
      return;
    }
    // 取消防抖  --- 海图消息要求实时性高
    store.dispatch("app/setSystemSocketData", data);
  };
  return socketInstance;
}
/**
 * 关闭 WebSocket 连接
 */
function closeWebSocket() {
  if (!socketInstance) return;
  clearInterval(socketKeep);
  if (socketInstance.readyState === SOCKET_READYSTATE) {
    // OPEN
    socketInstance.close();
  }
  socketInstance = null;
  window.systemSocket = null;
}
// 使用防抖处理 WebSocket 消息
// eslint-disable-next-line no-unused-vars
const handleSocketMessage = debounce((data) => {
  store.dispatch("app/setSystemSocketData", data);
}, 100);
/**
 * 防抖函数
 * @param {Function} fn - 要执行的函数
 * @param {number} delay - 延迟时间
 * @returns {Function} - 防抖后的函数
 */
function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}
